package com.lagou.homework;

import java.util.HashMap;

/*编程获取两个指定字符串中的最大相同子串。
        如： s1="asdafghjka", s2="aaasdfg" 他们的最大子串为"asd"
        提示： 将短的那个串进行长度依次递减的子串与较长的串比较。*/

public class Homework2 {

    public static void getMaxSameSubString(StringBuilder str1, StringBuilder str2) {
        StringBuilder shortstr = str1.length() > str2.length() ? str2 : str1;
        StringBuilder longstr = str1.length() > str2.length() ? str1 : str2;
        HashMap map = new HashMap();
        for (int i = 0; i <= shortstr.length(); i++) {
            for (int j = 0; j < i; j++) {
                //System.out.println("[" + shortstr.substring(j, i) + "]");
                if (!"".equals(shortstr.substring(j, i)) && String.valueOf(longstr).contains(shortstr.substring(j, i))) {
                    map.put(shortstr.substring(j, i), shortstr.substring(j, i).length());
                }
            }
        }

        int max = 0;
        for (Object len : map.values()) {
            max = Math.max(max, Integer.parseInt(String.valueOf(len)));
        }

        for (Object key : map.keySet()) {
            int keyLength = Integer.parseInt(String.valueOf(map.get(key)));
            if (max == keyLength) {
                System.out.println("最大相同子串是: " + key);
            }
        }
    }

    public static void main(String[] args) {
        StringBuilder stb1 = new StringBuilder("SaSasdasdfgfghjka");
        StringBuilder stb2 = new StringBuilder("aSSasdfg");
        getMaxSameSubString(stb1, stb2);
    }
}
